package com.yuyue.springFramework.note03.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * jdk动态代理方式二：直接创建代理类对象
 */
public class CostInvocationHandler2 implements InvocationHandler {
    //被代理对象
    private Object target;
    public CostInvocationHandler2(Object target){
        this.target = target;
    }

    //重写执行方法，将被代理对象的方法作为参数传入，处理被代理对象方法执行前后的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long startTime = System.nanoTime();

        //执行被代理对象方法，并获取其返回值
        Object object =  method.invoke(this.target, args);

        long endTime = System.nanoTime();
        System.out.println(method.getName() + "耗时（纳秒）：" + (endTime - startTime));

        return object;
    }

    //创建代理类对象
    public static <T> T createProxy(Object target, Class<T> T){
        //获取代理对象
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new CostInvocationHandler2(target));
    }
}
